package models

import (
	"github.com/astaxie/beego/orm"
	"gosync/utils"
)

type Machine struct {
	Id                 	int `json:"id"`
	Ip           		string `json:"ip"`
	Username           	string `json:"username"`
	Remark            	string `json:"remark"`
	BaseTable
}
type MachineQueryParam struct {
	BaseQueryParam
}


func (mc *Machine) TableName() string {
	return "qi_machine"
}
func (pj *Machine) BindTableName() string {
	return "qi_bind_mc"
}

//通过ID获取记录
func (mc *Machine) GetOne(id int) (*Machine, error){
	o := orm.NewOrm()
	mc.Id = id
	err := o.Read(mc)
	if err != nil {
		return nil, err
	}
	return mc, nil
}
//改成面向对象方式
func (mc *Machine) EditMc() (int64, error) {
	o := orm.NewOrm()
	mc.BaseTable.Updated_at = utils.GetNowTime()

	if num, err := o.Update(mc, "Id", "Ip", "Username", "Remark", "Updated_at"); err == nil {
		return num, err
	}else{
		return 0, err
	}
}
//删除机器
func (mc *Machine) DelMc(id int)(int64, error){
	o := orm.NewOrm()
	mc.Id = id

	//删除关联数据
	o.Raw(" DELETE FROM "+mc.BindTableName()+" WHERE `machine_id` = ?", id).Exec()

	if num, err := o.Delete(mc); err == nil {
		return num, err
	}else{
		return 0, err
	}
}

//获取无分页所有数据
func (mc *Machine) AllList() ([]*Machine){
	query := orm.NewOrm().QueryTable(mc.TableName())
	data := make([]*Machine, 0)
	query.OrderBy("-Id").All(&data)
	return data
}

//获取分页数据
func MachinePageList(pagenum int) ([]*Machine, int64) {
	m := Machine{}
	query := orm.NewOrm().QueryTable(m.TableName())
	data := make([]*Machine, 0)

	limit := (pagenum-1)*10
	total, _ := query.Count()
	query.OrderBy("-Id").Limit(10, limit).All(&data)
	return data, total
}





//添加机器
func AddMc(param Machine) error {
	o := orm.NewOrm()
	param.BaseTable.Created_at = utils.GetNowTime()
	param.BaseTable.Updated_at = utils.GetNowTime()
	// 插入数据
	_, err := o.Insert(&param)
	if err != nil {
		return err
	}
	return nil
}
